// 创建请求实例
const request = {
  baseURL: 'http://localhost:8080',
  timeout: 10000,
  headers: {
    'Content-Type': 'application/json',
  }
}

// 请求拦截器
const requestInterceptor = (config) => {
  // 从 localStorage 获取 token
  const token = localStorage.getItem('token')
  if (token) {
    config.headers.Authorization = `Bearer ${token}`
  }
  return config
}

// 响应拦截器
const responseInterceptor = (response) => {
  if (response.ok) {
    return response.json()
  } else {
    throw new Error(`HTTP error! status: ${response.status}`)
  }
}

// 通用请求方法
const fetchWithTimeout = async (url, options, timeout = 10000) => {
  const controller = new AbortController()
  const timeoutId = setTimeout(() => controller.abort(), timeout)
  
  try {
    const response = await fetch(url, {
      ...options,
      signal: controller.signal
    })
    clearTimeout(timeoutId)
    return response
  } catch (error) {
    clearTimeout(timeoutId)
    if (error.name === 'AbortError') {
      throw new Error('请求超时')
    }
    throw error
  }
}

// 通用请求方法
const requestMethod = async (method, endpoint, data = null) => {
  const config = {
    method,
    headers: { ...request.headers }
  }
  
  // 应用请求拦截器
  const interceptedConfig = requestInterceptor(config)
  
  if (data && method !== 'GET') {
    interceptedConfig.body = JSON.stringify(data)
  }
  
  try {
    const response = await fetchWithTimeout(
      `${request.baseURL}${endpoint}`,
      interceptedConfig,
      request.timeout
    )
    
    const responseData = await responseInterceptor(response)
    
    // 如果返回的状态码为200，说明接口请求成功，可以正常拿到数据
    if (responseData.code === 200) {
      return responseData
    } else {
      // 否则的话抛出错误
      throw new Error(responseData.message || '请求失败')
    }
  } catch (error) {
    if (error.response) {
      const { status, data } = error.response
      switch (status) {
        case 401:
          // 未授权，清除 token 并跳转到登录页
          localStorage.removeItem('token')
          localStorage.removeItem('userInfo')
          window.location.href = '/login'
          break
        case 403:
          console.error('没有权限访问该资源')
          break
        case 404:
          console.error('请求的资源不存在')
          break
        case 500:
          console.error('服务器内部错误')
          break
        default:
          console.error(`请求失败: ${data?.message || '未知错误'}`)
      }
    } else {
      console.error('网络错误，请检查您的网络连接')
    }
    throw error
  }
}

// 登录接口
export const login = (data) => {
  return requestMethod('POST', '/auth/login', data)
}

// 获取用户信息
export const getUserInfo = () => {
  return requestMethod('GET', '/auth/user-info')
}

// 登出接口
export const logout = () => {
  return requestMethod('POST', '/auth/logout')
}

// 导出请求实例
export default {
  get: (endpoint) => requestMethod('GET', endpoint),
  post: (endpoint, data) => requestMethod('POST', endpoint, data),
  put: (endpoint, data) => requestMethod('PUT', endpoint, data),
  delete: (endpoint) => requestMethod('DELETE', endpoint)
}
